<template>
  <!-- 新增 -->
  <el-dialog
    v-el-drag-dialog
    title="新增客户"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form v-show="activeTabName === 'customer'" ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="100px">
      <el-form-item label="客户名称" prop="csmName">
        <el-input v-model="temp.csmName" :maxlength="30" clearable @input="csmNameChange" />
      </el-form-item>
      <el-form-item label="客户编号" prop="csmCode">
        <el-input v-model="temp.csmCode" :maxlength="20" placeholder="单行输入" clearable>
          <el-button slot="append" class="append-search" @click.prevent="getCsmCode">获取</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="客户类型" prop="csmType">
        <el-select v-model="temp.csmType" placeholder="请选择">
          <el-option
            v-for="item in csmTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电话" prop="csmRgPhone">
        <el-input v-model="temp.csmRgPhone" :maxlength="15" clearable />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input v-model="temp.contact" :maxlength="30" clearable />
      </el-form-item>
      <el-form-item label="就近门市" prop="orgSNNo" class="block">
        <el-tree-select
          v-model="temp.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择所属单位',
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="地址" prop="csmRgAddress" class="block">
        <el-cascader v-if="visible" ref="cascader" v-model="temp.area" style="width: 40%;" :props="addressProps" clearable />
        <el-input v-model="temp.csmRgAddress" :maxlength="50" style="width: 35%;" />
        <el-button type="primary" icon="el-icon-location" style="width: 70px;" size="mini" @click="location">定位</el-button>
        <el-input-number v-model="temp.csmFloor" controls-position="right" :min="1" :max="7" :precision="0" style="width: 100px;" /> 层
      </el-form-item>
      <el-form-item label="客户等级" prop="unCheckQuality">
        <el-select v-model="temp.unCheckQuality" placeholder="请选择">
          <el-option
            v-for="item in customerQualityMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="sfzh">
        <el-input v-model="temp.sfzh" :maxlength="18" clearable />
      </el-form-item>
      <el-form-item label="身份证姓名" prop="sfzName">
        <el-input v-model="temp.sfzName" />
      </el-form-item>
      <el-form-item label="身份证地址" prop="sfzAddress" class="block no-bottom-form-item">
        <el-input v-model="temp.sfzAddress" />
      </el-form-item>
      <el-divider />
      <el-form-item label="证件类型" prop="cardType">
        <el-select v-model="temp.cardType" placeholder="请选择">
          <el-option
            v-for="item in cardTypeAll"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="证件编号" prop="cardNo">
        <el-input v-model="temp.cardNo" :maxlength="20" placeholder="单行输入">
          <el-button slot="append" class="append-search" @click.prevent="getCardNo">获取</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="开户类型" prop="newType">
        <el-select v-model="temp.newType" placeholder="请选择">
          <el-option
            v-for="item in newTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="默认支付方式" prop="defaultPaymentMethod">
        <el-select v-model="temp.defaultPaymentMethod" placeholder="请选择">
          <el-option
            v-for="item in paymentMethodMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源" prop="newFrom">
        <el-select v-model="temp.newFrom" placeholder="请选择">
          <el-option
            v-for="item in customerFromPlatMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售员" prop="salesmanName">
        <el-input v-model="temp.salesmanName" readonly>
          <el-button v-if="!temp.salesmanName" slot="append" class="append-search" @click="openSalesman">获取</el-button>
          <el-button v-else slot="append" class="append-search" @click.prevent="clearSalesman">清除</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="是否自提" prop="isPickUp">
        <el-select v-model="temp.isPickUp" placeholder="请选择">
          <el-option
            v-for="(value, key) in isPickUpMap"
            :key="key"
            :label="value"
            :value="Number(key)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="结款方式" prop="settlementType">
        <el-select v-model="temp.settlementType" placeholder="请选择">
          <el-option
            v-for="item in settlementTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开户日期" prop="createTime">
        <el-date-picker
          v-model="temp.createTime"
          placeholder="选择日期"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="合同号" prop="contractNumber">
        <el-input v-model="temp.contractNumber" />
      </el-form-item>
      <el-form-item label="授信额度" prop="decimalSpare1">
        <el-input v-model="temp.decimalSpare1" @input="temp.decimalSpare1=temp.decimalSpare1.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" />
      </el-form-item>
      <el-form-item label="结款天数" prop="intSpare2">
        <el-input-number v-model="temp.intSpare2" controls-position="right" :min="0" :precision="0" style="width: 100px;" />
      </el-form-item>
      <el-form-item label-width="90px" label="客户备注" prop="remark" class="block">
        <el-input v-model="temp.remark" type="textarea" :rows="2" :maxlength="200" show-word-limit />
      </el-form-item>
      <el-divider />
      <el-form-item label="备用字段1" prop="strSpare1">
        <el-input v-model="temp.strSpare1" :maxlength="30" />
      </el-form-item>
      <el-form-item label="备用字段2" prop="strSpare2">
        <el-input v-model="temp.strSpare2" :maxlength="30" />
      </el-form-item>
      <el-form-item label="备用字段3" prop="strSpare3">
        <el-input v-model="temp.strSpare3" :maxlength="50" />
      </el-form-item>
      <el-form-item label="备用字段4" prop="strSpare4">
        <el-input v-model="temp.strSpare4" :maxlength="50" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <!-- <el-button :loading="$loadingPlugin.depositRegister" type="primary" @click="depositRegister">
        押金登记
      </el-button> -->
      <el-button type="primary" @click="success(1)">
        保存
      </el-button>
    </div>
    <location ref="location" />
    <salesman ref="salesman" :tree-data="treeData" />
    <normalReceiptsAdd ref="normalReceiptsAdd" />
  </el-dialog>
</template>

<script>
  import { selectAreaCode, queryAddCsmDefaultData, queryOrgCode, customerAdd } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { csmLevelMap, defaultPaymentMethodMap, csmFromPlatMap, isPickUpMap } from '@/utils/map'
  import Location from './Location'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import Salesman from './Salesman'
  import NormalReceiptsAdd from '@/views/components/NormalReceiptsAdd'

  export default {
    name: 'add-csm',
    components: {
      Location, Salesman, NormalReceiptsAdd
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      const validateSfzh = (rule, value, callback) => {
        const sp1 = this.corpSettingData.sp1
        // 启用实名制开户
        if ((sp1 >> 30) & 0x01 > 0) {
          if (value === '') {
            callback(new Error('请输入身份证号'))
          }
          callback()
        }
        callback()
      }
      return {
        activeTabName: 'customer',
        cuindex: '',
        cardTypeAll: [],
        cardTypeAllList: [],
        ck: 0,
        csmCode: '',
        csmId: 0,
        customerLerel: 0,
        optFlag: undefined,
        cardInfo_temp: null, // 临时保存过滤的证件列表中身份证类型数据
        customerFromPlatMap: [],
        customerQualityMap: [],
        csmTypeMap: [],
        newTypeMap: [],
        paymentMethodMap: [],
        settlementTypeMap: [],
        csmLevelMap,
        defaultPaymentMethodMap,
        csmFromPlatMap,
        isPickUpMap,
        visible: false,
        type: 'add',
        currentOrg: null,
        currentSalesman: null,
        point: null,
        temp: {
          area: [],
          csmName: '',
          csmCode: '',
          csmType: 1,
          csmRgPhone: '',
          contact: '',
          orgSNNo: '',
          csmFloor: 1,
          unCheckQuality: '',
          sfzh: '',
          sfzName: '',
          sfzAddress: '',
          cardType: '',
          cardNo: '',
          newType: 2,
          defaultPaymentMethod: 1,
          newFrom: 8,
          salesmanName: '',
          isPickUp: 0,
          settlementType: 1,
          createTime: '',
          contractNumber: '',
          decimalSpare1: '',
          intSpare2: '',
          remark: '',
          strSpare1: '',
          strSpare2: '',
          strSpare3: '',
          strSpare4: ''
        },
        rules: {
          csmName: [{ required: true, message: '请输入客户名称', trigger: 'change' }],
          csmCode: [{ required: true, message: '请输入客户编号', trigger: 'change' }],
          contact: [{ required: true, message: '请输入联系人', trigger: 'change' }],
          csmRgAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
          orgSNNo: [{ required: true, message: '请选择就近门市', trigger: 'change' }],
          sfzh: [{ validator: validateSfzh, trigger: 'blur' }]
        },
        addressProps: {
          lazy: true,
          lazyLoad(node, resolve) {
            const { level, value } = node
            mergeAsyncFunc(selectAreaCode, { areaCode: value || 0 })
              .then((res) => {
                const nodes = res.data.map(item => ({
                  value: item.areaCode,
                  label: item.areaName,
                  leaf: level >= 3
                }))
                resolve(nodes)
              })
              .catch(() => {
                node.loading = false
                node.loaded = false
              })
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'corpSettingData'
      ])
    },
    methods: {
      async open(temp) {
        await this.getDefaultData()
        await this.init()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            this.type = 'edit'
          }
        })
      },
      init() {
        if (this.customerQualityMap['1'] && this.customerQualityMap['1'] === '普通') {
          this.temp.unCheckQuality = 1
        }
      },
      async getDefaultData() {
        const res = await queryAddCsmDefaultData({
          csmCode: this.temp.csmCode,
          audit: 0
        })
        this.cardTypeAll = JSON.parse(res.data.cardType)
        // 前端处理过滤身份证类型枚举，方便后期放开此类型
        for (let i = 0; i < this.cardTypeAll.length; i++) {
          if (this.cardTypeAll[i].value === 3) {
            this.cardTypeAll.splice(i, 1)
            break
          }
        }
        this.cardTypeAllList = JSON.parse(res.data.cardTypeAllList)
        this.ck = Number(res.data.ck)
        this.csmCode = res.data.csmCode
        this.csmLerel = Number(res.data.csmLerel)
        this.csmTypeMap = JSON.parse(res.data.customerType)
        this.customerFromPlatMap = JSON.parse(res.data.customerFromPlat)
        this.customerQualityMap = JSON.parse(res.data.customerQuality)
        this.newTypeMap = JSON.parse(res.data.newType)
        this.paymentMethodMap = JSON.parse(res.data.paymentMethod)
        this.settlementTypeMap = JSON.parse(res.data.settlementType)
      },
      // 获取客户编号
      async getCsmCode() {
        const res = await queryOrgCode({
          codeType: 2
        })
        this.temp.csmCode = res.data
      },
      // 清除销售员
      clearSalesman() {
        this.$set(this.temp, 'salesmanName', '')
        this.currentSalesman = null
      },
      // 获取证件编号
      async getCardNo() {
        const res = await queryOrgCode({
          codeType: 18
        })
        this.temp.cardNo = res.data
      },
      // 点击获取销售员
      async openSalesman() {
        const res = await this.$refs.salesman.open()
        this.currentSalesman = res
        this.$set(this.temp, 'salesmanName', res.userName)
      },
      csmNameChange(value) {
        this.temp.contact = value
      },
      depositRegister() {
        this.success(0)
        this.visible = false
        this.$refs.normalReceiptsAdd.open()
      },
      success(type) {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const csmTypeInfo = this.temp.csmType
          const sp5 = this.corpSettingData.sp5
          if (sp5 >> 13 & 0x01) {
            if (!this.temp.csmCode) {
              if (csmTypeInfo === 2 || csmTypeInfo === 4) {
                if (!this.temp.cardNo) {
                  this.$message('证件不能为空')
                  return
                } else {
                  if (this.temp.cardType !== 4) {
                    this.$message.warning('证件类型必须为营业执照')
                    return
                  }
                }
              }
            } else {
              // const flag = true
              // var rows = _this.grid_cardList.datagrid('getRows')
              // console.log(rows)
              // if (csmTypeInfo == 2 || csmTypeInfo == 4) {
              //   for (var i = 0; i < rows.length; i++) {
              //     if (rows[i].cardType == 4) {
              //       flag = false
              //       break
              //     }
              //   }
              //   if (flag) {
              //     $dlh.toast.wrong('营业执照不能为空')
              //     return
              //   }
              // }
            }
          }
          const customerInfo = {
            csmId: this.temp.csmId,
            csmCode: this.temp.csmCode,
            csmName: this.temp.csmName,
            sfzh: this.temp.sfzh,
            sfzName: this.temp.sfzName,
            sfzAddress: this.temp.sfzAddress,
            csmRgPhone: this.temp.csmRgPhone,
            contact: this.temp.contact,
            csmRgAddress: this.temp.csmRgAddress,
            nearStation: this.currentOrg.orgId,
            nearStationName: this.currentOrg.orgName,
            orgSNNo: this.currentOrg.orgSNNo,
            cardType: this.temp.cardType,
            cardNo: this.temp.cardNo,
            newType: this.temp.newType,
            defaultPaymentMethod: this.temp.defaultPaymentMethod,
            csmType: this.temp.csmType,
            newFrom: this.temp.newFrom,
            salesman: this.temp.salesman || 0,
            remark: this.temp.remark,
            createTime: this.temp.createTime ? moment(this.temp.createTime).format() : new Date(),
            settlementType: this.temp.settlementType,
            contractNumber: this.temp.contractNumber,
            strSpare1: this.temp.strSpare1,
            strSpare2: this.temp.strSpare2,
            strSpare3: this.temp.strSpare3,
            strSpare4: this.temp.strSpare4
          }
          const address = this.$refs.cascader.getCheckedNodes()[0]
          if (address) {
            const pathNodes = address.pathNodes
            customerInfo.provinceName = pathNodes[0].label
            customerInfo.provinceCode = pathNodes[0].value
            customerInfo.cityName = pathNodes[1].label
            customerInfo.cityCode = pathNodes[1].value
            customerInfo.countryName = pathNodes[2].label
            customerInfo.countryCode = pathNodes[2].value
            customerInfo.streetName = pathNodes[3].label
            customerInfo.streetCode = pathNodes[3].value
          } else {
            customerInfo.provinceName = ''
            customerInfo.provinceCode = ''
            customerInfo.cityName = ''
            customerInfo.cityCode = ''
            customerInfo.countryName = ''
            customerInfo.countryCode = ''
            customerInfo.streetName = ''
            customerInfo.streetCode = ''
          }
          // 客户等级
          if (this.customerLerel === 1) { // 没有用字典
            customerInfo.csmQuality = this.temp.unCheckQuality
          } else {
            customerInfo.unCheckQuality = this.temp.unCheckQuality
          }
          if (this.currentSalesman) {
            customerInfo.salesmanName = this.currentSalesman.salesmanName
          }
          if (type === 2 || (type === 0 && this.ck !== 0)) {
            customerInfo.csmStatus = 2
          }
          if (!this.temp.csmId && (this.corpSettingData.sp1 >> 5 & 0x01) === 0x01) {
            customerInfo.csmStatus = 1
          }
          if (this.temp.isPickUp === 0 && this.temp.csmId > 0) {
            customerInfo.isPickUp = -1
          }
          const f = this.temp.csmFloor // 楼层
          const maxF = this.corpSettingData.sp1 >> 18 & 0xF
          if (maxF > 0) {
            if (f > maxF) {
              this.$message('楼层不能超过' + maxF + '层')
              return
            }
          }
          // 经度纬度
          if (this.point) {
            customerInfo.lat = this.point.lat
            customerInfo.lng = this.point.lng
          }
          customerInfo.phoneItems = [{
            csmPhone: customerInfo.csmRgPhone,
            contact: customerInfo.contact,
            isMain: 1
          }]
          customerInfo.addressItems = [{
            csmAddress: customerInfo.csmRgAddress,
            provinceCode: customerInfo.provinceCode,
            provinceName: customerInfo.provinceName,
            cityCode: customerInfo.cityCode,
            cityName: customerInfo.cityName,
            countryCode: customerInfo.countryCode,
            countryName: customerInfo.countryName,
            streetCode: customerInfo.streetCode,
            streetName: customerInfo.streetName,
            orgId: customerInfo.nearStation,
            orgName: customerInfo.nearStationName,
            orgSNNo: customerInfo.orgSNNo,
            isMain: 1,
            csmFloor: this.temp.csmFloor || 1,
            longitude: customerInfo.lon,
            latitude: customerInfo.lat
          }]
          const decimalSpare1 = this.temp.decimalSpare1
          if (decimalSpare1 !== '') {
            customerInfo.decimalSpare1 = decimalSpare1
          }
          const intSpare2 = this.temp.intSpare2
          if (intSpare2 !== '') {
            customerInfo.intSpare2 = intSpare2
          }
          // //安全合同
          // var contract = $("#select_100_crm_cuw_contract").combobox("getValue");
          // if(contract == 1){
          //   customerInfo.csmOption |= 1<<3;
          // }else if(contract == 2){
          //   customerInfo.csmOption |= 1<<4;
          // }
          if (this.type === 'add') {
            this.add(customerInfo)
          } else {
            this.edit()
          }
        })
      },
      async add(params) {
        await customerAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit() {
        // await roleUpdate(this.temp)
        this.resolve(this.temp)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      // 定位
      async location() {
        const res = await this.$refs.location.open()
        console.log('详细地址信息', res)
        this.point = res.point
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
      },
      reset() {
        this.temp = {
          area: [],
          csmName: '',
          csmCode: '',
          csmType: 1,
          csmRgPhone: '',
          contact: '',
          orgName: '',
          csmFloor: 1,
          unCheckQuality: '',
          sfzh: '',
          sfzName: '',
          sfzAddress: '',
          cardType: '',
          cardNo: '',
          newType: 2,
          defaultPaymentMethod: 1,
          newFrom: 8,
          salesmanName: '',
          isPickUp: 0,
          settlementType: 1,
          createTime: '',
          contractNumber: '',
          decimalSpare1: '',
          intSpare2: '',
          strSpare1: '',
          strSpare2: '',
          strSpare3: '',
          strSpare4: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  //justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
